import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))

import requests
import json
from reqapi.api import BaseApi
from dataclasses import dataclass
from typing import Optional
from com.db.order_account_manager import OrderAccountManager

# 报价状态常量
class OfferStatus:
    """报价状态常量"""
    OFFERING = 1  # 报价中
    SUCCESS = 3   # 报价成功
    
    @staticmethod
    def get_status_desc(status: int) -> str:
        """获取状态描述"""
        status_map = {
            OfferStatus.OFFERING: "报价中",
            OfferStatus.SUCCESS: "报价成功"
        }
        return status_map.get(status, "未知状态")

@dataclass
class GetOfferStatusRequest:
    """获取报价状态请求模型"""
    orderNo: str
    Sessionid: str

@dataclass
class GetOfferStatusData:
    """报价状态数据模型"""
    status: int
    orderNo: str
    failReason: Optional[str] = None
    
    @property
    def status_desc(self) -> str:
        """获取状态描述"""
        return OfferStatus.get_status_desc(self.status)

@dataclass
class GetOfferStatusResponse:
    """获取报价状态响应模型"""
    code: int
    msg: str
    timestamp: int
    data: Optional[GetOfferStatusData] = None

class GetOfferStatusApi(BaseApi):
    def execute(self, order_no: str) -> GetOfferStatusResponse:
        """
        获取报价状态 API
        
        Args:
            order_no: 订单号
            
        Returns:
            GetOfferStatusResponse: 响应结果
        """
        url = f"{self.BASE_URL}/api/youpin/bff/trade/v1/order/sell/delivery/get-offer-status"
        
        # 构建请求数据
        request = GetOfferStatusRequest(
            orderNo=order_no,
            Sessionid=self.device_id
        )
        headers = self.common_headers.copy()
        request_data = request.__dict__
        print("请求头:")
        print(json.dumps(headers, indent=2, ensure_ascii=False))
        print(f"请求数据: {json.dumps(request_data, indent=2, ensure_ascii=False)}")
        try:
            response = self.interceptor.send_request(url, json=request_data, headers=headers, need_encrypt=False)
            print("=== 响应信息 ===")
            if isinstance(response, dict):
                result = response
            elif hasattr(response, 'json'):
                result = response.json()
            else:
                result = response
            print(f"响应数据: {json.dumps(result, indent=2, ensure_ascii=False)}")
            if not isinstance(result, dict):
                raise Exception(f"响应数据格式错误: {result}")
            data = result.get('data')
            status_data = None
            if isinstance(data, dict):
                status_data = GetOfferStatusData(
                    status=data.get('status', 0),
                    orderNo=data.get('orderNo', ''),
                    failReason=data.get('failReason')
                )
            return GetOfferStatusResponse(
                code=result.get('code', -1),
                msg=result.get('msg', ''),
                timestamp=result.get('timestamp', 0),
                data=status_data
            )
        except Exception as e:
            print(f"请求失败: {e}")
            return GetOfferStatusResponse(
                code=-1,
                msg=f"请求异常: {e}",
                timestamp=0,
                data=None
            )


def main():
    """测试获取报价状态 API"""
    try:
        # 从下单账号管理器获取ID为1的账号
        account_manager = OrderAccountManager()
        account = account_manager.get_account_by_id(1)
        
        if not account:
            print("无法获取ID为1的账号")
            return
        
        device_id = account.get('device_id', '')
        auth_token = account.get('uu_token', '')
        uk = account.get('uk', '')
        

        
        # 创建API实例
        api = GetOfferStatusApi(
            device_token=device_id,
            device_id=device_id,
            auth_token=auth_token,
            uk=uk
        )
        
        # 测试获取报价状态
        order_no = "2025021311008316118"
        response = api.execute(order_no)
        if response.data:
            print(f"获取报价状态结果: {response}")
            print(f"订单 {response.data.orderNo} 当前状态: {response.data.status_desc}")
        
    except Exception as e:
        print(f"测试失败: {str(e)}")


if __name__ == "__main__":
    main()
